const websocket = {
    start () {
        console.log('start')
        const that = this
        // 清除延时器
        this.timeoutObj && clearTimeout(this.timeoutObj)
        this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj)
        this.timeoutObj = setTimeout(() => {
            console.log('this.websocket :', this.websocket)
            if (that.websocket && that.websocket.readyState == 1) {
                console.log('进入发送心跳包')
                that.websocket.send('heartbreath') // 发送消息，服务端返回信息，即表示连接良好，可以在socket的onmessage事件重置心跳机制函数
            } else {
                console.log('心跳包失败，重新链接')
                that.reconnect()
            }
            // 定义一个延时器等待服务器响应，若超时，则关闭连接，重新请求server建立socket连接
            this.serverTimeoutObj = setTimeout(() => {
             this.websocket.close();
            }, this.timeout)
        }, this.timeout)
    },
    reset () { // 重置心跳
        // 清除时间
        clearTimeout(this.timeoutObj)
        clearTimeout(this.serverTimeoutObj)
        // 重启心跳
        this.start()
    },
    // 重新连接
    reconnect () {
        if (this.lockReconnect) return
        this.lockReconnect = true
        // 没连接上会一直重连，设置延迟避免请求过多
        this.timeoutnum && clearTimeout(this.timeoutnum)
        this.timeoutnum = setTimeout(() => {
        this.initWebSocket()
        this.lockReconnect = false
        }, this.timeout)
        },
        async setOnmessageMessage (event) {
        console.log(event.data, '获得消息')
        this.reset()
        // 自定义全局监听事件
        window.dispatchEvent(new CustomEvent('onmessageWS', {
        detail: {
            data: event.data
        }
        }))
        // //发现消息进入    开始处理前端触发逻辑
        // if (event.data === 'success' || event.data === 'heartBath') return
    },
    websocketonopen () {
        // 开启心跳
        const that = this
        let timer
        timer = setInterval(function () {
        that.start()
        }, that.timeout)
        // this.start();   //因为我这边一直报心跳延时，所以我添加了setInterval来发送心跳
        console.log('WebSocket连接成功!!!' + new Date() + '///////////' + this.websocket.readyState)
    },
    websocketonerror (e) {
        console.log('WebSocket连接发生错误' + e)
    },
    websocketclose (e) {
        this.websocket.close()
        clearTimeout(this.timeoutObj)
        clearTimeout(this.serverTimeoutObj)
        console.log('WebSocket连接关闭')
    },
    websocketsend (messsage) {
			const that = this
      that.websocket.send(messsage)
    },
    closeWebSocket () { // 关闭websocket
			const that = this
      that.websocket.close()
    }

}

export default websocket